/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ExperimentExecution.java
 *
 * Created on Jan 22, 2010, 1:47:42 PM
 */
package ch.epfl.dslab.conferrng.wizard;

import ch.epfl.dslab.conferrng.engine.FaultInjectionEngine;
import ch.epfl.dslab.conferrng.engine.FaultInjectionPlan;
import ch.epfl.dslab.conferrng.engine.InjectionResult;
import ch.epfl.dslab.conferrng.gui.ResultTableRenderer;
import java.awt.Dimension;
import java.awt.Point;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JEditorPane;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.netbeans.spi.wizard.WizardPage;

/**
 *
 * @author slv
 */
public class ExperimentExecution extends WizardPage {

    public static final String PROP_FAULTINJECTIONENGINE = "faultInjectionEngine";

    /**
     * Get the value of faultInjectionEngine
     *
     * @return the value of faultInjectionEngine
     */
    public FaultInjectionEngine getFaultInjectionEngine() {
        return faultInjectionEngine;
    }

    /**
     * Set the value of faultInjectionEngine
     *
     * @param faultInjectionEngine new value of faultInjectionEngine
     */
    public void setFaultInjectionEngine(FaultInjectionEngine faultInjectionEngine) {
        FaultInjectionEngine oldFaultInjectionEngine = this.faultInjectionEngine;
        this.faultInjectionEngine = faultInjectionEngine;

        experimentOutcomeTable.getColumnModel().getColumn(1).setCellRenderer(new ResultTableRenderer(faultInjectionEngine));

        firePropertyChange(PROP_FAULTINJECTIONENGINE, oldFaultInjectionEngine, faultInjectionEngine);
    }

    /** Creates new form ExperimentExecution */
    public ExperimentExecution() {
        initComponents();
    }

    @Override
    protected void renderingPage() {
        System.out.println("Starting experiments");
        faultInjectionEngine.setPlan(faultInjectionPlan);
        faultInjectionEngine.start(faultInjectionPlan.getErrorGenerators());
    }
    public static final String PROP_FAULTINJECTIONPLAN = "faultInjectionPlan";

    /**
     * Get the value of faultInjectionPlan
     *
     * @return the value of faultInjectionPlan
     */
    public FaultInjectionPlan getFaultInjectionPlan() {
        return faultInjectionPlan;
    }

    /**
     * Set the value of faultInjectionPlan
     *
     * @param faultInjectionPlan new value of faultInjectionPlan
     */
    public void setFaultInjectionPlan(FaultInjectionPlan faultInjectionPlan) {
        FaultInjectionPlan oldFaultInjectionPlan = this.faultInjectionPlan;
        this.faultInjectionPlan = faultInjectionPlan;
        firePropertyChange(PROP_FAULTINJECTIONPLAN, oldFaultInjectionPlan, faultInjectionPlan);
    }

    public static String getDescription() {
        return "Experiments execution";
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        faultInjectionPlan = new ch.epfl.dslab.conferrng.engine.FaultInjectionPlan();
        faultInjectionEngine = new ch.epfl.dslab.conferrng.engine.FaultInjectionEngine();
        jLabel1 = new javax.swing.JLabel();
        jProgressBar1 = new javax.swing.JProgressBar();
        jScrollPane1 = new javax.swing.JScrollPane();
        experimentOutcomeTable = new javax.swing.JTable();
        stopButton = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        pathToFile = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();

        jLabel1.setText("Progress");

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${faultInjectionEngine.percentage}"), jProgressBar1, org.jdesktop.beansbinding.BeanProperty.create("value"));
        bindingGroup.addBinding(binding);

        experimentOutcomeTable.setModel(new  javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Name", "Type"
            }));

            org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create("${faultInjectionEngine.results}");
            org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, eLProperty, experimentOutcomeTable);
            org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${description}"));
            columnBinding.setColumnName("Description");
            columnBinding.setColumnClass(String.class);
            columnBinding.setEditable(false);
            columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${errorType}"));
            columnBinding.setColumnName("Error Type");
            columnBinding.setColumnClass(Integer.class);
            columnBinding.setEditable(false);
            columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${isResilient}"));
            columnBinding.setColumnName("Resilient");
            columnBinding.setColumnClass(Boolean.class);
            columnBinding.setEditable(false);
            bindingGroup.addBinding(jTableBinding);
            jTableBinding.bind();
            experimentOutcomeTable.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    experimentOutcomeTableMouseClicked(evt);
                }
            });
            jScrollPane1.setViewportView(experimentOutcomeTable);
            experimentOutcomeTable.getColumnModel().getColumn(0).setResizable(false);
            experimentOutcomeTable.getColumnModel().getColumn(1).setResizable(false);
            experimentOutcomeTable.getColumnModel().getColumn(1).setCellRenderer(new ResultTableRenderer(faultInjectionEngine));
            experimentOutcomeTable.getColumnModel().getColumn(2).setResizable(false);

            stopButton.setText("STOP");

            binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, faultInjectionEngine, org.jdesktop.beansbinding.ELProperty.create("!${running}"), stopButton, org.jdesktop.beansbinding.BeanProperty.create("selected"));
            bindingGroup.addBinding(binding);

            stopButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    stopButtonActionPerformed(evt);
                }
            });

            jButton1.setText("Save");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
                }
            });

            jLabel2.setText("Save Resilience Profile?");

            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
            this.setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel1)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jProgressBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 436, Short.MAX_VALUE)
                            .addContainerGap())
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addComponent(stopButton)
                            .addGap(176, 176, 176))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jLabel2)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(pathToFile, javax.swing.GroupLayout.PREFERRED_SIZE, 269, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 498, Short.MAX_VALUE))
                            .addContainerGap())))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel1))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(stopButton)
                    .addGap(5, 5, 5)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jButton1)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(pathToFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2)))
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );

            bindingGroup.bind();
        }// </editor-fold>//GEN-END:initComponents

    private void stopButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stopButtonActionPerformed
        faultInjectionEngine.stop();
    }//GEN-LAST:event_stopButtonActionPerformed

    private void experimentOutcomeTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_experimentOutcomeTableMouseClicked
        Point p = evt.getPoint();
        int row = experimentOutcomeTable.rowAtPoint(p);

        InjectionResult result = faultInjectionEngine.getResults().get(row);


        JEditorPane htmlDisplay = new JEditorPane();
        htmlDisplay.setEditable(false);
        htmlDisplay.setContentType("text/html");
        htmlDisplay.setText(result.toHtml());

        JScrollPane pane = new JScrollPane(htmlDisplay);

        pane.setPreferredSize(new Dimension(700, 600));


        JOptionPane.showMessageDialog(this, pane, "Test output", JOptionPane.PLAIN_MESSAGE);
    }//GEN-LAST:event_experimentOutcomeTableMouseClicked

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        List<InjectionResult> results = faultInjectionEngine.getResults();
        Element element = new Element("ResilienceProfile");
        for (InjectionResult result : results) {
            element.addContent(result.toXML());
        }
        Document doc = new Document(element);
        XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
        try {
            outputter.output(doc, new FileOutputStream(pathToFile.getText()));
        } catch (IOException ex) {
            Logger.getLogger(ExperimentExecution.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton1ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable experimentOutcomeTable;
    private ch.epfl.dslab.conferrng.engine.FaultInjectionEngine faultInjectionEngine;
    private ch.epfl.dslab.conferrng.engine.FaultInjectionPlan faultInjectionPlan;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField pathToFile;
    private javax.swing.JButton stopButton;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
}
